package com.patch.update;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.patch.AppUpdate;
import com.patch.MyPatch;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class UpdateAppManager extends AsyncTask<String, Integer, Void> {
    // 下载应用存放全路径
    private String FILE_NAME;

    private String FILE_PATCH_NAME;
    public String PACKAGE_NAME = "EMPTY";
    public String DOWNLOAD_URL = "EMPTY";
    public String DOWNLOAD_PATCH_URL = "EMPTY";//差分包下载路径
    public String OLD_VERSION = "EMPTY";//上一个版本号
    public String FILE_PATH = "EMPTY";//上一个版本号

    private boolean fileStatus = true;//创建文件状态

    private final WeakReference<Context> weakContext;//避免内存泄漏
    // 进度条的当前刻度值
    private int curProgress;

    private ProgressDialog pd1 = null;

    private boolean patch = false;//是否增量更新
    private long apkFileLength;

    public UpdateAppManager(Context context, String apkPath, String packageNmae, String downUrl, String downPatchUrl, String oldVersion) {
        this.weakContext = new WeakReference<>(context);
        FILE_NAME = apkPath + File.separator + "app.apk";
        FILE_PATCH_NAME = apkPath + File.separator + "my.patch";
        FILE_PATH = apkPath;
        PACKAGE_NAME = packageNmae;
        DOWNLOAD_URL = downUrl;
        DOWNLOAD_PATCH_URL = downPatchUrl;
        OLD_VERSION = oldVersion;
    }

    /**
     * 安装新版本应用
     */
    private void installApp() {
        File appFile = null;
        Context context = weakContext.get();
        if (context == null) {
            // Context 已被回收，停止操作
            return;
        }
        if (!fileStatus) {
            Toast.makeText(context, "文件下载路径创建失败，请检查是有文件读写权限再重新更新", Toast.LENGTH_SHORT).show();
            return;
        }
        if (patch) {
            String oldApkPath = AppUpdate.getInstance().getOldApkPath(context, PACKAGE_NAME);
            if (oldApkPath != null) {
                boolean make = MyPatch.make(oldApkPath, FILE_NAME, FILE_PATCH_NAME);
                if (!make) {
                    pd1.dismiss();
                    showDialog("安装包下载错误，是否重新下载");
                    return;
                }
            }
        }
        if (pd1.isShowing()) {
            pd1.dismiss();
        }
        appFile = new File(FILE_NAME);

        if (!appFile.exists()) {
            Toast.makeText(context, "安装包下载错误，是否重新下载", Toast.LENGTH_LONG).show();
            pd1.dismiss();
            showDialog("安装包下载错误，是否重新下载");
            return;
        }
        long length;
        if (patch) {
            File file = new File(FILE_PATCH_NAME);
            length = file.length();

        } else {
            length = appFile.length();
        }
        if (length < apkFileLength) {
            pd1.dismiss();
            showDialog("安装包未下载完整，是否重新下载");
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(context, PACKAGE_NAME + ".fileprovider", appFile);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(install);
        } else {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        }

    }

    @Override
    protected Void doInBackground(String... params) {
        Context context = weakContext.get();
        if (context == null) {
            return null;
        }
        URL url = null;
        InputStream in = null;
        FileOutputStream out = null;
        HttpURLConnection conn = null;
        try {
            /**
             * 开始下载前删除以前的APK
             */
            try {
                File apkFile = new File(FILE_NAME);
                if (apkFile.exists()) {
                    apkFile.delete();
                }
                File patchFile = new File(FILE_PATCH_NAME);
                if (patchFile.exists()) {
                    patchFile.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            String downloadUrl = DOWNLOAD_URL;
            String fileName = FILE_NAME;
            //获取APK当前版本
            String versionID = AppUpdate.getInstance().getVersion(context);
            patch = false;
            String oldApkPath = AppUpdate.getInstance().getOldApkPath(context, PACKAGE_NAME);
            if (versionID.equalsIgnoreCase(OLD_VERSION) && oldApkPath != null) {
                if (DOWNLOAD_PATCH_URL != null && !"".equalsIgnoreCase(DOWNLOAD_PATCH_URL)) {
                    downloadUrl = DOWNLOAD_PATCH_URL;
                    fileName = FILE_PATCH_NAME;
                    patch = true;
                }
            }

            url = new URL(downloadUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3600000);
            conn.connect();
            apkFileLength = conn.getContentLength();
            long fileLength = conn.getContentLength() + 5242880;//增加5M
            in = conn.getInputStream();
            File filePath = new File(FILE_PATH);
            if (!filePath.exists()) {
                boolean mkdir = filePath.mkdir();
                if (!mkdir) {
                    boolean mkdirs = filePath.mkdirs();
                    if (!mkdirs) {
                        fileStatus = false;
                        return null;
                    }
                }
            }
            out = new FileOutputStream(new File(fileName));
            byte[] buffer = new byte[1024];
            int len = 0;
            long readedLength = 0L;

            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                readedLength += len;
                int tempProgress = (int) (((float) readedLength / fileLength) * 100);
                if (tempProgress - curProgress > 5) {
                    curProgress = tempProgress;
                    publishProgress(curProgress);
                }
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Context context = weakContext.get();
        if (context == null) {
            return;
        }
        pd1 = new ProgressDialog(context);
        //依次设置标题,内容,是否用取消按钮关闭,是否显示进度
        pd1.setTitle("软件更新中");
        pd1.setMessage("请稍后...");
        pd1.setCancelable(false);
        pd1.setMax(100);
        pd1.setButton("取消更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cancel(true);
                pd1.dismiss();
            }
        });
        //这里是设置进度条的风格,HORIZONTAL 是水平进度条,SPINNER 是圆形进度条
        pd1.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd1.setIndeterminate(false);
        //调用 show() 方法将 ProgressDialog 显示出来
        pd1.show();
        publishProgress(1);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        pd1.dismiss();
        installApp();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Log.e("Constants.TAG", values[0] + "");
        if (values[0] == 100) {
            pd1.setProgress(0);
        } else {
            pd1.setProgress(values[0]);
        }
    }


    private void showDialog(String message) {
        Context context = weakContext.get();
        if (context == null) {
            return;
        }
        new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE)
                .setTitleText("提示")
                .setContentText(message)
                .setConfirmText("重新下载")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        new UpdateAppManager(context, FILE_PATH, PACKAGE_NAME, DOWNLOAD_URL, DOWNLOAD_PATCH_URL, OLD_VERSION).execute();
                    }
                })
                .setCancelText("暂不下载")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                })
                .show();
    }
}
